package com.imy.luascript.retrofit;

import android.util.Log;

import com.imy.luascript.app.data.BaseResponse;

import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;


import javax.net.ssl.SSLHandshakeException;


import rx.Subscriber;

/**
 * 接口返回数据判断(返回接口数据结构为BaseResponse<T>)
 *
 * @author: Imy
 * @date: 2017-03-06
 */
public abstract class HttpResultSubscriber<T> extends Subscriber<BaseResponse<T>> {
  public static final String TAG = "HttpResultSubscriber";

  @Override
  public void onCompleted() {

  }

  @Override
  public void onError(Throwable e) {
    Log.i(TAG, "onError: " + e.toString());
    e.printStackTrace();

  }

  /**
   * 过滤出是不是证书时间异常（手机调过期时间）
   * @param e
   * @return
   */
  private boolean isCertTimeException(Throwable e){
    boolean yes = false;
    if(e instanceof SSLHandshakeException){
      while (e != null){
        if(e instanceof CertificateNotYetValidException || e instanceof CertificateExpiredException){
          yes = true;
          break;
        }
        e = e.getCause();
      }
    }
    return yes;
  }
  @Override
  public void onNext(BaseResponse<T> t) {
    if (t != null) {
        if (t.getError_code()==BaseResponse.SUCCESS){
            onSuccess(t);
        }else {
          onError(new ApiException(ERROR.CODE_ERROR,t.getError_message()));
        }
    }else {
      onError(new ApiException(ERROR.UNKNOWN,"unknown"));
    }
  }

  public abstract void onSuccess(T t);

  public void onSuccess(BaseResponse<T> t) {
    if (t != null) {
      onSuccess(t.getData());
    }
  }



  public abstract void onError(ApiException e);
}
